<template>
  <el-header class="header" :class="{'admin-header': user && user.role !== 'CUSTOMER', 'mobile-header': isMobile}">
    <!-- Logo -->
    <div class="logo">图易通</div>

    <!-- 汉堡按钮（仅在移动端显示） -->
    <div v-if="isMobile" class="hamburger" @click.stop="toggleSidebar">
      <i class="el-icon-menu"></i>
    </div>

    <!-- 导航菜单 - PC 显示 -->
    <el-menu
      v-if="user && user.role === 'CUSTOMER' && !isMobile"
      :router="true"
      mode="horizontal"
      class="nav"
      background-color="#fff"
      text-color="#ccc"
      active-text-color="#6ec1e4"
      default-active="/home/userUpload"
    >
      <el-menu-item index="/home/userUpload">上传图片</el-menu-item>
      <el-menu-item index="/home/userHistory">历史记录</el-menu-item>
    </el-menu>

    <!-- 用户头像 -->
    <div class="user-avatar" ref="avatarRef">
      <el-popover
        placement="bottom-end"
        :width="isMobile ? 100 : 150"
        trigger="manual"
        v-model="visible"
        popper-class="user-popover"
        transition="fade"
      >
        <div class="popover-content">
          <el-button type="text"  @click="showUserInfoDialog = true; visible=false;">修改信息</el-button>
          <el-button type="text" @click="logout">退出登录</el-button>
        </div>
        <img
          slot="reference"
          :src="user.headimgurl"
          alt="头像"
          class="avatar"
          @click.stop="togglePopover"
        />
      </el-popover>
    </div>

    <!-- 移动端侧边栏 -->
    <transition name="slide-fade">
      <div v-if="sidebarVisible && isMobile" class="mobile-sidebar">
        <el-menu
          :router="true"
          mode="vertical"
          class="popup-menu"
          background-color="#2c2c2c"
          text-color="#eee"
          active-text-color="#6ec1e4"
          default-active="/home/UserUpload"
        >
          <el-menu-item @click="toggleSidebar" index="/home/UserUpload">上传图片</el-menu-item>
          <el-menu-item @click="toggleSidebar" index="/home/UserHistory">历史记录</el-menu-item>
        </el-menu>
      </div>
    </transition>

    <!-- 编辑信息弹窗 - PC 使用 -->
    <el-dialog
      title="个人信息"
      :visible.sync="showUserInfoDialog"
      width="500px"
      custom-class="user-info-dialog"
      :close-on-click-modal="false"
      :modal="false"
      :modal-append-to-body="false"
      v-if="!isMobile"
    >
      <el-form :model="form" label-width="100px" class="user-edit-form">
        <el-form-item label="用户昵称">
          <el-input v-model="form.nickname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="form.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showUserInfoDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEditUserInfo">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 编辑信息弹窗 - 移动端使用 -->
    <transition name="slide-up">
      <div class="mobile-popup" v-if="showUserInfoDialog && isMobile">
        <div class="mask" @click.self="showUserInfoDialog = false"></div>
        <div class="popup-content">
          <h3>个人信息</h3>
          <el-form :model="form" label-position="top">
            <el-form-item label="用户昵称">
              <el-input v-model="form.nickname" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话号码">
              <el-input v-model="form.phone" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div class="popup-footer">
            <el-button @click="showUserInfoDialog = false" block>取消</el-button>
            <el-button type="primary" @click="submitEditUserInfo" block>提交</el-button>
          </div>
        </div>
      </div>
    </transition>
  </el-header>
</template>

<script>
import axios from 'axios'

export default {
  name: 'HeaderComponent',
  data() {
    return {
      visible: false,
      sidebarVisible: false,
      showUserInfoDialog: false,
      isMobile: window.innerWidth <= 768,
      form: {
        id: '',
        nickname: '',
        phone: '',
        role: ''
      },
      originalUser: {}
    }
  },
  computed: {
    user() {
      return this.$store.state.user
    }
  },
  watch: {
    showUserInfoDialog(val) {
      if (val) {
        this.form = {
          id: this.user.id,
          nickname: this.user.nickname,
          phone: this.user.phone,
          role: this.user.role
        }
        this.originalUser = { ...this.form }
      }
    }
  },
  methods: {
    togglePopover() {
      this.visible = !this.visible
    },
    submitEditUserInfo() {
      const changes = {}

      for (const key in this.form) {
        if (this.form[key] !== this.originalUser[key]) {
          if (key !== 'nickname' && key !== 'phone') {
            alert(`禁止修改字段：${key}`)
            return
          } else {
            changes[key] = this.form[key]
          }
        }
      }

      if (Object.keys(changes).length === 0) {
        alert('未检测到任何修改')
        return
      }
      var url='/api/user/updatePersonalInformationById';
      if(this.user?.role != 'CUSTOMER'){
        url='/api/admin/updatePersonalInformationById';
      }
      axios.post(url, {
        id: this.form.id,
        nickname: changes.nickname || this.form.nickname,
        phone: changes.phone || this.form.phone
      }).then(res => {
        if (res.data.code == 1) {
          this.user.phone=res.data.data.phone;
          this.user.nickname=res.data.data.nickname;
          this.$store.commit('setUser', this.user)
          this.showUserInfoDialog = false
          this.visible = false
        } else {
          alert(res.data.msg || '更新失败')
        }
      }).catch(err => {
        alert('请求失败：' + err.message)
      })
    },
    logout() {
      axios.get('/api/login/logout').catch(() => {})
      this.$router.push({ path: '/login' })
    },
    handleResize() {
      this.isMobile = window.innerWidth <= 768
    },
    toggleSidebar() {
      this.sidebarVisible = !this.sidebarVisible
    },
    handleClickOutside(e) {
      // 关闭侧边栏
      if (
        this.sidebarVisible &&
        this.isMobile &&
        !e.target.closest('.mobile-sidebar') &&
        !e.target.closest('.hamburger')
      ) {
        this.sidebarVisible = false
      }

      // 关闭用户菜单
      if (!e.target.closest('.user-avatar')) {
        this.visible = false
      }
    }
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
    document.addEventListener('click', this.handleClickOutside)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    document.removeEventListener('click', this.handleClickOutside)
  }
}
</script>

<style scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  height: 60px;
  position: sticky;
  top: 0;
  z-index: 1000;
  transition: all 0.3s ease;
}

.hamburger {
  font-size: 1.8rem;
  cursor: pointer;
  color: #ccc;
  display: none;
  transition: transform 0.3s ease;
}

.hamburger:hover {
  transform: rotate(90deg);
}

.mobile-header .hamburger {
  display: block;
}

.logo {
  font-size: 1.6rem;
  font-weight: bold;
  color: #6ec1e4;
  cursor: pointer;
  white-space: nowrap;
  flex-shrink: 0;
}

.nav {
  flex-grow: 1;
  display: flex;
  justify-content: center;
}

.nav .el-menu {
  display: flex;
  justify-content: center;
  background-color: transparent !important;
}

.nav .el-menu-item {
  height: 60px;
  line-height: 60px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
  text-align: center;
  padding: 0 20px;
  color: #ccc;
}

.user-avatar {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.avatar:hover {
  transform: scale(1.1);
}

.popover-content {
  padding: 8px 0;
  display: flex;
  flex-direction: row; /* 改为水平排列 */
  justify-content: space-between; /* 可选：两边对齐 */
  align-items: center; /* 垂直居中 */
  text-align: left;
  background-color: #2c2c2c;
  border-radius: 4px;
}

.popover-content .el-button {
  width: auto;
  min-width: 40px;
  max-width: 80px;
  font-size: 13px;
  padding: 6px 8px;
  text-align: left;
  border-radius: 4px;
  color: #eee;
  transition: background-color 0.3s ease, color 0.3s ease;
}

.popover-content .el-button:hover {
  background-color: #3f3f3f;
  color: #6ec1e4;
}

/* 弹窗样式 */
.user-info-dialog .el-dialog__body {
  padding: 20px;
}

.user-edit-form .el-form-item {
  margin-bottom: 20px;
}

/* 移动端侧边栏 */
.mobile-sidebar {
  position: fixed;
  top: 60px;
  left: 0;
  bottom: 0;
  background-color: #2c2c2c;
  z-index: 1001;
  overflow-y: auto;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.3);
  width: 130px;
}

.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}

/* 移动端弹窗样式 */
.mobile-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  display: flex;
  align-items: flex-end;
}

.mobile-popup .mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.mobile-popup .popup-content {
  background-color: #fff;
  width: 100%;
  max-height: 80vh;
  padding: 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  transform: translateY(0);
  transition: transform 0.3s ease;
  overflow-y: auto;
}

.mobile-popup .popup-content h3 {
  margin-top: 0;
  font-size: 1.1rem;
  margin-bottom: 16px;
}

.mobile-popup .popup-footer {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 20px;
}

/* 进场动画 */
.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}
.slide-up-enter {
  transform: translateY(100%);
  opacity: 0;
}
.slide-up-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

@media (max-width: 768px) {
  .header {
    justify-content: space-between; /* 使汉堡按钮和用户头像分别位于两侧 */
    position: space-between;
  }

  .hamburger {
    position: absolute;
    left: 20px;
    z-index: 1;
  }

  .logo {
    margin: 0 auto;
    text-align: center;
    font-size: 1.4rem;
    width: 100%;
    display: block;
    position: relative;
    z-index: 0;
  }

  .user-avatar {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    z-index: 1;
    display: flex;
    align-items: center;
  }

  /* 侧边栏定位 */
  .mobile-sidebar {
    position: fixed;
    top: 79px; /* 上边缘与导航条底部对齐，并下移10px */
    left: 0;
    bottom: 0;
    width: 120px;
    background-color: #2c2c2c;
    z-index: 1001;
    overflow-y: auto;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.3);
    padding-top: 10px;
  }

  .popup-menu {
    border-right: none;
  }
}

</style>